/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package scribd.core;

import com.google.code.javascribd.connection.ScribdClient;
import com.google.code.javascribd.connection.ScribdConnectionException;
import com.google.code.javascribd.connection.StreamableData;
import com.google.code.javascribd.docs.ChangeSettings;
import com.google.code.javascribd.docs.ChangeSettingsResponse;
import com.google.code.javascribd.docs.GetDownloadUrl;
import com.google.code.javascribd.docs.GetDownloadUrlResponse;
import com.google.code.javascribd.docs.GetSettings;
import com.google.code.javascribd.docs.GetSettingsResponse;
import com.google.code.javascribd.docs.Search;
import com.google.code.javascribd.docs.SearchResponse;
import com.google.code.javascribd.docs.Upload;
import com.google.code.javascribd.docs.UploadResponse;
import com.google.code.javascribd.type.Access;
import com.google.code.javascribd.type.ApiKey;
import com.google.code.javascribd.type.DocumentId;
import com.google.code.javascribd.type.FileData;
import com.google.code.javascribd.type.License;
import com.google.code.javascribd.type.ResponseStatus;
import com.google.code.javascribd.type.SearchScope;
import com.google.code.javascribd.type.SecretKey;
import com.google.code.javascribd.type.SessionKey;
import com.google.code.javascribd.type.ShowAds;
import com.google.code.javascribd.user.Login;
import com.google.code.javascribd.user.LoginResponse;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author pokemon
 */
public class ScribdProcessor {

    private ScribdClient client = new ScribdClient();
    private ApiKey apiKey = new ApiKey("5zousnetcoaksavrtvvbo");
    private String username = "";
    private String password = "";
    private int userid;
    private SessionKey sessionKey;
    private String errorMessage = "";
    private String realname = "";
    private String accessKey = "";

    private Proxy proxy = null;

    public ScribdProcessor() {
//        SocketAddress sa = new InetSocketAddress("192.168.1.2", 3128);
//        client.setProxy(new Proxy(Proxy.Type.HTTP, sa));
    }

    public void setProxy(String host, int port) {
        SocketAddress sa = new InetSocketAddress(host, port);
        client.setProxy(new Proxy(Proxy.Type.HTTP, sa));
    }

    public boolean login(String username, String password) throws ScribdConnectionException, IOException, Exception {

        Login login = new Login(apiKey, username, password);
        this.username = username;
        this.password = password;

        LoginResponse response = client.execute(login);        

        if (response.getStatus() == ResponseStatus.OK) {
            realname = response.getName();
            sessionKey = response.getSessionKey();
            userid = response.getUserId();
            System.out.println("---ScribdProcessor@login---");
            System.out.println(" Username: "+username);
            System.out.println(" Password: "+password);
            System.out.println(" Realname: "+realname);
            System.out.println("---ScribdProcessor@login---");
            return true;
        } else {
            errorMessage = response.getError().getMessage();
            throw new Exception(response.getError().getMessage());            
        }
                
    }

    public ArrayList search(String query) throws ScribdConnectionException, IOException, Exception {
        ArrayList searchResult = new ArrayList();

        Search search = new Search(apiKey, query);
        search.setScope(SearchScope.ALL);

        SearchResponse response = client.execute(search);

        if (response.getStatus()==ResponseStatus.OK) {
            for (SearchResponse.Entry result : response.getResultSet().getEntries()) {
                //System.out.printf("%d - %s\n", result.getDocId().intValue(), result.getTitle());
                searchResult.add(new ScribdDocument(result.getDocId().intValue(), result.getTitle(), result.getDescription(), result.getTags(), result.getPageCount().intValue()));
            }
        } else {
            throw new Exception("Scribd search failed.");
        }

        return searchResult;
    }

    public int upload(File file) throws ScribdConnectionException, IOException, Exception {
        StreamableData uploadData = new FileData(file);

        Upload upload = new Upload(apiKey, uploadData);
        upload.setDocType("pdf");
        upload.setAccess(Access.PUBLIC);

        UploadResponse response = client.execute(upload);
        ResponseStatus status = response.getStatus();

        System.out.printf("document_id: %d\n", response.getDocId().intValue());
        System.out.printf("document_id: %s\n", response.getAccessKey());

        int result = 0;
        if (status==ResponseStatus.OK) {
             result = response.getDocId().intValue();
             accessKey = response.getAccessKey();
        } else {
            throw new Exception(response.getError().getMessage());
        }

        return result;
    }

    public Object download(int documentId, String documentType) throws ScribdConnectionException, IOException {
        URL result = null;        

        GetDownloadUrl download = new GetDownloadUrl(apiKey, new DocumentId(documentId), documentType);
        //download.setSessionKey(sessionKey);
        download.setMyUserId("pub-99921174804225002803");
        download.setSecretKey(new SecretKey("sec-6hz78vpgu6lesfl0ufvakoc05l"));

        GetDownloadUrlResponse response = client.execute(download);

        ResponseStatus status = response.getStatus();
        if (status == ResponseStatus.OK) {
            result = response.getDownloadLink();
            return result;
        } else {
            errorMessage = response.getError().getMessage();
            return errorMessage;
        }
    }

    public boolean changeSetting(int documentId, String title, String description, String tags) throws ScribdConnectionException, IOException, Exception {
        boolean result = false;
        ChangeSettings cs = new ChangeSettings(apiKey);
//        cs.setSessionKey(sessionKey);
        cs.setDocId(new DocumentId(documentId));
        cs.setTitle(title);
        cs.setDescription(description);
        cs.setTags(tags);
        cs.setEdition("1");
        cs.setAccess(Access.PUBLIC);
        cs.setLicense(License.PD);
        cs.setShowAds(ShowAds.TRUE);
        cs.setWhenPublished("20090630");
        cs.setAuthor(realname);
        cs.setPublisher("www.amrishodiq.co.cc");
        cs.setLinkBackURL(new URL("http://amrishodiq.wordpress.com"));

        System.out.println("---ScribdProcessor@changeSetting---");
        System.out.println(" My user id: "+username);
        System.out.println(" Author: "+realname);
        System.out.println("---ScribdProcessor@changeSetting---");

        ChangeSettingsResponse response = client.execute(cs);
        ResponseStatus status = response.getStatus();
        if (status == ResponseStatus.OK) {
            result = true;
        } else {
            throw new Exception(response.getError().getMessage());
        }
        return result;
    }

    public void getSettings() throws ScribdConnectionException, IOException {
        //http://www.scribd.com/doc/16846801/Tutorial-Dasar-Pemrograman-Google-Maps-API
        GetSettings gs = new GetSettings(apiKey, new DocumentId(16846801));
        GetSettingsResponse response = client.execute(gs);
        ResponseStatus status = response.getStatus();
        if (status==ResponseStatus.OK) {
            System.out.println("Doc ID   : "+response.getDocId().intValue());
            System.out.println("Title    : "+response.getTitle());
            System.out.println("Author   : "+response.getAuthor());
            System.out.println("Edition  : "+response.getEdition());
            System.out.println("Publisher: "+response.getPublisher());
            System.out.println("Access   : "+response.getAccessKey());
            System.out.println("Tags     : "+response.getTags());
            System.out.println("Page     : "+response.getPageCount());
            System.out.println("Ads      : "+response.getShowAds().value());
        } else {
            System.out.println(response.getError().getMessage());
        }
        
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public static void main(String[] args) {
        ScribdProcessor sp = new ScribdProcessor();
        sp.setProxy("192.168.1.2", 3128);
        try {
            sp.login("amrishodiq", "Ultimate10");
            sp.getSettings();
            sp.changeSetting(16952171, "Ganti judul", "Nyoba ganti judul", "ganti,judul");
        } catch (ScribdConnectionException ex) {
            Logger.getLogger(ScribdProcessor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ScribdProcessor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(ScribdProcessor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
